from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import traceback
import allure
class Base:
    def __init__(self,driver):
        self.driver = driver
        self.select_loctor = {
            "id":By.ID,
            "name":By.NAME,
            "class name":By.CLASS_NAME,
            "xpath":By.XPATH,
            "css":By.CSS_SELECTOR,
            "link text":By.LINK_TEXT,
            "partial link text":By.PARTIAL_LINK_TEXT,
            "tag name":By.TAG_NAME
        }
        # self.driver = driver

    def find_element(self,loctor_method,loc):
        """
        :param loctor_method:  要传入操作的哪个类型
        :param loc:  要操作的元素
        :return:  返回elemnt
        """
        try:
            elelemt = WebDriverWait(self.driver,10,0.5).until(EC.presence_of_element_located((self.select_loctor[loctor_method],loc)))
            return elelemt
        except Exception as e:
            traceback.print_exc()
            allure.attach(self.driver.get_screenshot_as_png(),name='失败截图',attachment_type = allure.attachment_type.PNG) # 报错的截图 生成并且加载到allure报告里面
            raise e
    def find_elements(self,loctor_methd,loc,num):
        """
        :param loctor_methd: 传入操作的哪个类型
        :param loc:  要操作的元素
        :param num:  要操作的第几个
        :return:  返回element
        """
        try:
            ele = WebDriverWait(self.driver,10,0.5).until(EC.presence_of_all_elements_located((self.select_loctor[loctor_methd],loc)))[num]
            return ele
        except Exception as e:
            traceback.print_exc()
            allure.attach(self.driver.get_screenshot_as_png(), name='失败截图',
                          attachment_type=allure.attachment_type.PNG)  # 报错的截图 生成并且加载到allure报告里面
            raise e
    def click_element(self,locmethod,loc):
        """
        :param locmethod: 要操作哪种定位方式
        :param loc: 要操作的元素
        :return:
        """
        self.find_element(locmethod,loc).click()
    def click_elements(self,locmethod,loc,num):
        self.find_elements(locmethod,loc,num).click()
    def input_text(self,locmethod,loc,text):
        """
        先清除
        再输入
        :param locmethod: 要操作哪种元素定位方式
        :param loc: 要操作的元素
        :param text: 输入的文本内容
        :return:
        """
        ele = self.find_element(locmethod,loc)
        ele.clear()
        ele.send_keys(text)
    def input_texts(self,locmethod,loc,num,text):
        ele = self.find_elements(locmethod,loc,num)
        ele.clear()
        ele.send_keys(text)



    def handles_win(self,num=-1):
        """
        句柄切换
        :param num: 默认切换最后一个
        :return:
        """
        win = self.driver.window_handles
        self.driver.switch_to.window(win[num])








